<?php
// src/Pyaf/GymBundle/Controller/AvisoController.php
namespace Pyaf\GymBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Pyaf\GymBundle\Entity\Alumno;
use Pyaf\GymBundle\Entity\Clase;
use Pyaf\GymBundle\Entity\AvisoFalta;

/**
 * Description of AvisoController
 *
 * @author Toshiba P755-S5272
 */
class AvisoController extends Controller{
    
    public function listAlumnosAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $alumnos = $em->getRepository('PyafGymBundle:Alumno')->findEnablesOrderByNombre();
        
        return $this->render('PyafGymBundle:Aviso:listAlumnos.html.twig', array('alumnos' => $alumnos));
    }
    
    public function calendarioAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $clases = $em->getRepository('PyafGymBundle:Clase')->getClasesAlumno($id);
        $alumno = $em->getRepository('PyafGymBundle:Alumno')->find($id);
        $avisosFaltas = $em->getRepository('PyafGymBundle:AvisoFalta')->getFaltasAlumno($id);
      
        return $this->render('PyafGymBundle:Aviso:calendario.html.twig', 
                            array('idAlumno' => $id, 'Clases' => $clases,
                                  'alumno' => $alumno, 'avisosFaltas' => $avisosFaltas));
    }
    
    public function newFaltaAction() {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        $peticion = $this->getRequest();
        
        $em = $this->getDoctrine()->getEntityManager();
        
        $alumno = new Alumno();
        $clase = new Clase();
        $avisoFalta = new AvisoFalta();
        
        $alumno = $em->getRepository('PyafGymBundle:Alumno')->findAlumno($peticion->request->get('id_Alumno'));
        $clase = $em->getRepository('PyafGymBundle:Clase')->findById($peticion->request->get('id_Clase'));
        
        $avisoFalta->setAlumno($alumno);
        $avisoFalta->setClase($clase);
        
        $fecha = strtotime($peticion->request->get('fechaFalta'));
        $tiempo = explode("-", $clase->getCodigoClase());
        
        $fechaFalta = date("Y-m-l", $fecha);
        $fechaGrabar = date("Y-m-d", $fecha);
        $dayToDia = $this->dateToString($fechaFalta);
        
        if(($dayToDia != null) && ($dayToDia == $clase->getDia()) && ($fechaGrabar > (date("Y-m-d")))){
            $avisoFalta->setFechaFalta($fechaGrabar." ".$tiempo[0].":00:00");
            
            
            if(!$this->existFechaFaltaToAlumno($alumno->getId(), $avisoFalta->getFechaFalta())){
                $avisoFalta->setDia($dayToDia);
                $avisoFalta->setFechaAviso(date("Y-m-D H:i:s"));
                $avisoFalta->setLibre(true);

                $em->persist($avisoFalta);
                $em->flush();
                $em->clear();

                $jsonData = json_encode(array('success' => true, 'event'=>'success', 'diaEscogido' => $dayToDia, 'diaActividad' => $clase->getDia()));
            } else {
                
                $jsonData = json_encode(array('success' => true, 'event'=>'exist', 'diaEscogido' => $dayToDia, 'diaActividad' => $clase->getDia()));
            }
            
        } else {
            $jsonData = json_encode(array('success' => true, 'event'=>'fail', 'diaEscogido' => $dayToDia, 'diaActividad' => $clase->getDia()));
        }
        $response = new Response($jsonData);
        return $response;
    }
    
    public function deleteAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $em->getRepository('PyafGymBundle:AvisoFalta')->deleteDay($id);
    }

    public function dateToString($date){
        $dias = array(
            'Lunes'=>'Monday', 'Martes'=>'Tuesday',
            'Miércoles'=>'Wednesday','Jueves'=>'Thursday',
            'Viernes'=>'Friday');
        
        $fecha = explode("-", $date);
        
        foreach ($dias as $key => $day) {
            if($day == $fecha[2]){
                return $key;
                exit();
            }
        }
        return null;
    }
    
    /**
     * 
     * @param type $alumnoId. id de un alumno
     * @param type $fechaFalta. fecha de falta nueva
     * @return boolean. true si ya existe, false si es nueva
     */
    public function existFechaFaltaToAlumno($alumnoId, $fechaFalta) {
        $em = $this->getDoctrine()->getEntityManager();
        $avisosFaltas = $em->getRepository('PyafGymBundle:AvisoFalta')->getFaltasAlumno($alumnoId);
        
        foreach ($avisosFaltas as $value) {
            if($value->getFechaFalta() == $fechaFalta){
                return true;
                exit();
            }
        }
        return false;
    }
    
    /**************************************************************************/
    
     public function listDayAction() {
                
        return $this->render('PyafGymBundle:Recuperar:list.html.twig');
    }
    
    public function showCalendarioAction(){
        
        return $this->render('PyafGymBundle:Recuperar:show.html.twig');
    }
    
    /**
     * Metodo que lee de la base de datos el calendario y lo transforma en formato
     * Json para luego ser renderizado
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function jsonDataAction(){
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        $em = $this->getDoctrine()->getEntityManager();
        $calendario = $em->getRepository('PyafGymBundle:AvisoFalta')->retrieveAllFreeDays();
        
        $calendarioJson = array();
	
        foreach ($calendario as $value) {
            date_default_timezone_set('America/Argentina/Buenos_Aires');
            $date = new \DateTime($value->getFechaFalta());
            $fecha = $date->format('Y-m-d');
            $hs = $date->format('H')+1;
            
            $url = $this->get('router')->generate('avisos_recupera_add', array('id' => $value->getId()));
            
            $day = array(
                        'id' => $value->getId(),
			'title' => "Libre",
			'start' => $value->getFechaFalta(),
			'end' => "$fecha $hs:00:00",
                        'allDay' => false,
			'reservar' => $url
            );
            array_push($calendarioJson, $day);
        }
        
        $jsonData = json_encode($calendarioJson);
        $response = new Response($jsonData);
        return $response;
    }
    
    public function addRecuperaAction($id) {
        
        $em = $this->getDoctrine()->getEntityManager();
        $claseRecuperar = $em->getRepository('PyafGymBundle:AvisoFalta')->getFechaRecuperar($id);
        $alumnos = $em->getRepository('PyafGymBundle:Alumno')->findEnablesOrderByNombre();
        return $this->render('PyafGymBundle:Recuperar:add.html.twig', array('alumnos' => $alumnos, 'clase' => $claseRecuperar));
    }
    
    public function saveRecuperaAction(){
        $em = $this->getDoctrine()->getEntityManager();
        $peticion = $this->getRequest();
        $claseRecuperar = new AvisoFalta();
        $claseRecuperar = $em->getRepository('PyafGymBundle:AvisoFalta')->getFechaRecuperar($peticion->request->get('id_Clase'));
        
        $alumnoRecupera = new Alumno();
        $alumnoRecupera = $em->getRepository('PyafGymBundle:Alumno')->findAlumno($peticion->request->get('id_Alumno'));
        
        $claseRecuperar->setAlumnoRecupera($alumnoRecupera);
        $claseRecuperar->setLibre(false);
        
        $em->persist($claseRecuperar);
        $em->flush();
               
        $this->get('session')
             ->setFlash(
                           'alertaRecuperaSuccess',
                           'El alumno ('.$alumnoRecupera->getNombreCompleto().') 
                               asignado correctamente a la clase del día ('.$claseRecuperar->getClase()->getDia().')!'
                       );
        
        return $this->render('PyafGymBundle:Recuperar:list.html.twig');
    }
    
    public function calendarioRecuperaAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $avisosRecuperacion = $em->getRepository('PyafGymBundle:AvisoFalta')->getRecuperarAlumno($id);
      
        return $this->render('PyafGymBundle:Aviso:calendarioRecupera.html.twig', 
                            array('idAlumno' => $id, 'avisosRecuperaciones' => $avisosRecuperacion));
    }
    
    public function disabledAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $claseDevuelta = new AvisoFalta();
        $claseDevuelta = $em->getRepository('PyafGymBundle:AvisoFalta')->getFechaRecuperar($id);
        
        $claseDevuelta->setAlumnoRecupera();
        $claseDevuelta->setLibre(true);
        
        $em->persist($claseDevuelta);
        $em->flush();
    }
    
    public function showCalendarioFijoAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $clases = new Clase();
        $clasesAvisadas = new AvisoFalta();
        $clases = $em->getRepository('PyafGymBundle:Clase')->findAllOrderByNombre();
        $clasesAvisadas = $em->getRepository('PyafGymBundle:AvisoFalta')->retrieveAllDaysEmptyAlumno();
        $formatDays = $this->getStayDaysToCalendar();
        
        return $this->render('PyafGymBundle:Recuperar:showFijo.html.php', 
                            array('Clases' => $clases, 'ClasesAvisadas' => $clasesAvisadas,
                                  'formatDays' => $formatDays));
    }
    
    public function getStayDaysToCalendar() {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        $days = array(
                'Lunes'=>'Monday', 'Martes'=>'Tuesday',
                'Miércoles'=>'Wednesday','Jueves'=>'Thursday',
                'Viernes'=>'Friday', 'Sábado'=>'Saturday', 'Domingo'=>'Sunday');
        $startDay = "";
        foreach ($days as $key => $day) {
            if($day == date('l')){
                $startDay = $key;
            }
        }
        
        $currentDay = date('d-m-Y');
        $Date = strtotime($currentDay);
        
        switch ($startDay) {
            case 'Lunes':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+0 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+1 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+2 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+3 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+4 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Martes':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+6 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+0 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+1 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+2 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+3 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Miércoles':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+5 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+6 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+0 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+1 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+2 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Jueves':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+4 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+5 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+6 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+0 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+1 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Viernes':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+3 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+4 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+5 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+6 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+0 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Sábado':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+2 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+3 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+4 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+5 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+6 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            case 'Domingo':{
                $days['Lunes']      = date("d-m-Y",  strtotime('+1 days', $Date));
                $days['Martes']     = date("d-m-Y",  strtotime('+2 days', $Date));
                $days['Miércoles']  = date("d-m-Y",  strtotime('+3 days', $Date));
                $days['Jueves']     = date("d-m-Y",  strtotime('+4 days', $Date));
                $days['Viernes']    = date("d-m-Y",  strtotime('+5 days', $Date));
                $days['Aux']        = date("d-m-Y",  strtotime('+7 days', $Date));
                break;
            }
            default:
                break;
        }
        
        return $days;
    }
    
    public function addRecuperaFijoAction() {
        $peticion = $this->getRequest();
        $em = $this->getDoctrine()->getEntityManager();
        $alumnos = $em->getRepository('PyafGymBundle:Alumno')->findEnablesOrderByNombre();
        $clase = $em->getRepository('PyafGymBundle:Clase')->findById($peticion->request->get('idClase'));
        
        return $this->render('PyafGymBundle:Recuperar:addFijo.html.twig', array('alumnos' => $alumnos,
            'fecha' => $peticion->request->get('fecha'), 'clase' => $clase));
    }
    
    public function saveRecuperaFijoAction(){
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        $em = $this->getDoctrine()->getEntityManager();
        $peticion = $this->getRequest();
        
        $claseRecuperar = new AvisoFalta();
        
        $clase = new Clase();
        $clase = $em->getRepository('PyafGymBundle:Clase')->findById($peticion->request->get('id_Clase'));
        
        $alumnoRecupera = new Alumno();
        $alumnoRecupera = $em->getRepository('PyafGymBundle:Alumno')->findAlumno($peticion->request->get('id_Alumno'));
        
        $claseRecuperar->setAlumnoRecupera($alumnoRecupera);
        $claseRecuperar->setClase($clase);
        $claseRecuperar->setFechaFalta($peticion->request->get('fechaRecupera'));
        $claseRecuperar->setDia($clase->getDia());
        $claseRecuperar->setFechaAviso(date('Y-m-d H:i:s'));
        $claseRecuperar->setLibre(false);
        
        $em->persist($claseRecuperar);
        $em->flush();
        
        $this->get('session')
             ->setFlash(
                           'alertaRecuperaSuccess',
                           'El alumno ('.$alumnoRecupera->getNombreCompleto().') 
                               asignado correctamente a la clase del día ('.$claseRecuperar->getClase()->getDia().')!'
                       );
        
        return $this->render('PyafGymBundle:Recuperar:list.html.twig');
    }
}

?>
